package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.TimeUnit;

/**
 * 超时获取令牌
 *
 * @author yangyunjiao
 */
public class TimeoutRateLimiterExample {
    public static void main(String[] args) {
        RateLimiter rateLimiter = RateLimiter.create(2.0);

        for (int i = 0; i < 10; i++) {
            // 在指定超时时间内尝试获取令牌
            if (rateLimiter.tryAcquire(499, TimeUnit.MILLISECONDS)) {
                System.out.println("成功获取令牌，执行任务: " + i);
                processRequest(i);
            } else {
                System.out.println("超时未获取到令牌，任务被拒绝: " + i);
            }
        }
    }

    private static void processRequest(int id) {
        System.out.println("处理请求: " + id + " | 时间: " + System.currentTimeMillis());
    }
}
